package cn.fastpay.management.service.impl;

import cn.fastpay.core.exception.BaseException;
import cn.fastpay.management.entity.PermissionMenu;
import cn.fastpay.management.repository.PermissionMenuRepository;
import cn.fastpay.management.service.PermissionMenuService;
import cn.fastpay.management.exception.PermissionOperatorException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author freewolf
 */
@Service
public class PermissionMenuServiceImpl implements PermissionMenuService {

    @Autowired
    private PermissionMenuRepository permissionMenuRepository;

    @Override
    public void deleteById(Long id) {
        try{
            this.permissionMenuRepository.delete(id);
        } catch (ConstraintViolationException e){
            throw PermissionOperatorException.MENU_REMVOE_CONSTRAINT;
        }
    }

    @Override
    public void add(PermissionMenu menu) {
        if (menu.getId() != null) {
            throw BaseException.DB_INSERT_INCLUDE_ID;
        } else {
            this.permissionMenuRepository.save(menu);
        }
    }

    @Override
    public void update(PermissionMenu menu) {
        if(menu.getId() == null) {
            throw BaseException.DB_UPDATE_NOT_INCLUDE_ID;
        }
        this.permissionMenuRepository.save(menu);
    }

    @Override
    public PermissionMenu getById(Long id) {
        return this.permissionMenuRepository.findOne(id);
    }

    @Override
    public List<PermissionMenu> getAll() {
        return this.permissionMenuRepository.findAll();
    }
}
